<?php

namespace Grumpy\Reddit;

use Carbon\Carbon as Carbon;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Reddit {
  const LIMIT = 100;

  private $_username;
  private $_password;
  private $_modhash;
  private $_cookie;

  public function login($user, $pass) {
    $this->_username = $user;
    $this->_password = $pass;
    $data            = json_decode($this->_login());

    if (count($data->json->errors) == 0) {
      $this->_modhash = $data->json->data->modhash;
      $this->_cookie  = $data->json->data->cookie;
      return $data;
    } else {
      return false;
    }
  }

  public function userExists($username) {
    ///user/username/about.json
    $context = array(
        'http' => array(
            'header' => 'User-Agent: user profile counter v1.0 by /u/TessBell' . "\r\n" . 'Content-Type: application/x-www-form-urlencoded' . "\r\n",
            'method' => 'GET'
        )
    );
    $context = stream_context_create($context);
    try {
      $result = json_decode(@file_get_contents('http://www.reddit.com/user/' . $username . '/about.json', false, $context));
    } catch (ErrorException $e) {
      return false;
    }
    if (isset($result->data->name) && $result->data->name == $username) {
      return true;
    }
    return false;
  }

  public function getComments($username, $before, $after) {
    // if there is an after, and a before, only use the after
    $before = (!is_null($after) && !is_null($before)) ? null : $before;


    $data                          = http_build_query(
            array(
                'sort'     => 'new',
                't'        => 'all',
                'username' => $username,
                'after'    => $after,
                'before'   => $before,
                'count'    => self::LIMIT,
                'limit'    => self::LIMIT,
            )
    );
    $context                       = array(
        'http' => array(
            'header' => 'User-Agent: user profile counter v1.0 by /u/TessBell' . "\r\n" . 'Content-Type: application/x-www-form-urlencoded' . "\r\n",
            'method' => 'GET'
        )
    );
    $context                       = stream_context_create($context);
    $result                        = @file_get_contents('http://www.reddit.com/user/' . $username . '/comments.json?' . $data, false, $context);
    $json                          = json_decode($result);
    $results_raw                   = array('meta'     => array('before' => null,'after' => null), 'comments' => array());
    if(is_null($json)) {
      return $results_raw;
    }
    $results_raw['meta']['after']  = $json->data->after;
    $results_raw['meta']['before'] = $json->data->before;

    foreach ($json->data->children as $post) {
      if ($post->kind == 't1') {
        $created = intval($post->data->created_utc);

        $date                      = Carbon::createFromTimestamp($created);
        $array                     = array(
            'text'       => $post->data->body_html,
            'created'    => $date,
            'comment_id' => $post->data->id,
            'link_id'    => str_replace('t3_', '', $post->data->link_id),
            'subreddit'  => $post->data->subreddit
        );
        $results_raw['comments'][] = $array;
      }
    }

    return $results_raw;
  }

  private function _login() {
    $data    = http_build_query(array(
        'api_type' => 'json',
        'passwd'   => $this->_password,
        'rem'      => false,
        'user'     => $this->_username
    ));
    $context = array(
        'http' => array(
            'header'  => 'User-Agent: user profile counter v1.0 by /u/TessBell' . "\r\n" . 'Content-Type: application/x-www-form-urlencoded' . "\r\n",
            'method'  => 'POST',
            'content' => $data
        )
    );
    $context = stream_context_create($context);
    $result  = file_get_contents('https://ssl.reddit.com/api/login/' . $this->_username, false, $context);
    return $result;
  }

}

?>
